package cn.dengta.context.model;

import java.util.Calendar;
import java.util.Date;
import javax.annotation.Nullable;

import cn.dengta.common.model.ValueProxy;
import cn.dengta.common.model.ValueProxyImpl;
import cn.dengta.common.util.Common;
import lombok.Getter;
import me.codeplayer.util.EasyDate;
import me.codeplayer.util.X;

/**
 * 日期单位
 */
@Getter
public enum DateUnit implements ValueProxyImpl<DateUnit, Integer> {
	/** 天 */
	DAY(Calendar.DAY_OF_MONTH, "天", 1),
	/** 月 */
	MONTH(Calendar.MONTH, "月", 30),
	/** 年 */
	YEAR(Calendar.YEAR, "年", 360);

	public final Integer value;
	public final int field;
	public final int unit;
	final ValueProxy<DateUnit, Integer> proxy;

	// 构造函数，枚举类型只能为私有
	DateUnit(int field, String label, int unit) {
		this.field = field;
		this.unit = unit;
		this.value = ordinal();
		this.proxy = new ValueProxy<>(this, this.value, label);
	}

	public static final DateUnit[] CACHE = values();

	public static DateUnit of(@Nullable Integer value) {
		return Common.getEnum(CACHE, DateUnit::getValue, value);
	}

	public static DateUnit ofField(@Nullable Integer field) {
		return Common.getEnum(CACHE, DateUnit::getField, field);
	}

	public String getDesc(Integer limit) {
		return limit != null ? limit + (this == MONTH ? "个月" : this.getLabel()) : null;
	}

	public static String calcDesc(@Nullable Integer limit) {
		if (limit == null) {
			return null;
		}
		int unit;
		for (int i = CACHE.length - 1; i >= 0; i--) {
			DateUnit dateUnit = CACHE[i];
			if (limit >= (unit = dateUnit.getUnit()) && unit % limit == 0) {
				return dateUnit.getDesc(unit / limit);
			}
		}
		return DateUnit.DAY.getDesc(limit);
	}

	/**
	 * 在指定日期的基础上加上数量为limit、单位为当前单位时间值，并返回计算后的结果
	 *
	 * @param base 指定的基准日期
	 * @param limit 追加的期限值
	 */
	public Date add(@Nullable Date base, int limit) {
		EasyDate d = new EasyDate();
		X.use(base, d::setDate);
		d.getCalendar().add(field, limit);
		return d.toDate();
	}

}
